package testJdk.thread.pool.scheduledExecutorServiceTest;


import lombok.Data;
import lombok.SneakyThrows;

import java.util.concurrent.*;

/**
 * @author Created by cyd on 2021-03-29 17:54:42
 * @Description : 测试线程池的定时任务
 */
public class ScheduledExecutorServiceTest02 {
    public static void main(String[] args) {
        // 创建一个延迟执行的线程池
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(2, new ThreadFactory() {
            private int n;

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "自定义线程名称：" + n++);
            }
        });
        for (int i = 0; i < 10; i++) {
            ScheduledFuture<?> scheduledFuture = ses.scheduleAtFixedRate(new MyRunnable2(i), 1, 2, TimeUnit.SECONDS);
            scheduledFuture.cancel(true);

        }
        System.out.println("over");
    }
}

@Data
class MyRunnable2 implements Runnable {
    private int id;


    public MyRunnable2(int id) {
        this.id = id;
    }

    @SneakyThrows
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        Thread.sleep(1500);
        System.out.println(name + "线程-执行了任务:" + id);
    }
}